<template>
  <div class="global-container">
    <div class="global-header">
      <el-image
        style="width: 100px; height: 100px"
        :src="require('@/assets/header_images/current.png')"
      ></el-image>
      <div class="title">
        服务管理
        <div class="title-content">
          提供服务实例的生命周期管理能力，支持服务的启停、状态监控、资源升级、日志查看等功能。
        </div>
      </div>
    </div>
    <div class="searchDiv1">
      <div class="searchDiv global-operate">
        <span class="keyword">关键词：</span>
        <el-input
          v-model="searchInput"
          placeholder="通过服务名称、部署名称检索"
          clearable
          class="inputStyle"
          style="width: 20%"
          prefix-icon="el-icon-search"
          @input="filterServiceInstanceList"
        />
        <!-- <el-button type="primary" size="small" style="background-color: #304156; border-color: #304156;" @click="filterServiceInstanceList">查 询</el-button> -->
        <div style="float: right">
          <el-button
            type="primary"
            size="small"
            @click="startSelectInstances"
            class="el-button-primary-style"
          >启 动
          </el-button>

          <el-button
            type="primary"
            size="small"
            @click="stopSelectInstances"
            class="el-button-primary-style"
            style="margin-right: 10px"
          >停 止
          </el-button>
          <!-- <el-button type="primary" size="small" @click="deleteSelectInstances">删 除</el-button>-->
          <el-popconfirm
            title="确认删除服务实例？"
            @confirm="deleteSelectInstances"
          >
            <el-button
              type="primary"
              size="small"
              slot="reference"
              class="el-button-primary-style"
              style="margin-right: 10px"
              :disabled="selectInstanceList.length === 0"
            >
              删 除
            </el-button>
          </el-popconfirm>
        </div>
      </div>
    </div>
    <div>
      <div class="servicePackageList">
        <div style="height: 70vh">
          <div style="height: 64vh">
            <el-table
              :data="tableData"
              style="width: 100%"
              @selection-change="tableSelectionChange"
              ref="multipleTable"
            >
              <el-table-column
                type="selection"
                align="center"
              ></el-table-column>
              <el-table-column prop="appZhname" label="服务名称" width="150">
              </el-table-column>
              <el-table-column prop="deployName" label="部署名称" width="200">
              </el-table-column>
              <el-table-column label="服务描述">
                <template slot-scope="scope">
                  <el-tooltip
                    effect="dark"
                    :content="scope.row.appDescription"
                    placement="bottom-start"
                    popper-class="tooltipClass"
                    :disabled="isShowTooltip"
                  >
                    <div class="descSpan" @mouseover="onMouseOver($event)">
                      {{ scope.row.appDescription }}
                    </div>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="appVersion" label="服务版本" width="140">
              </el-table-column>
              <el-table-column
                prop="host"
                label="地址"
                width="200"
              ></el-table-column>
              <el-table-column prop="updateTime" label="创建时间" width="200">
              </el-table-column>
              <el-table-column label="状态" width="140">
                <template slot-scope="scope">
                  <el-tag
                    type="success"
                    size="medium"
                    v-if="showStatusTag(scope.row) === 2"
                  >
                    运行中
                  </el-tag>
                  <el-tag
                    type="info"
                    size="medium"
                    v-else-if="
                      showStatusTag(scope.row) === 3 ||
                      showStatusTag(scope.row) === 5 ||
                      showStatusTag(scope.row) === 0
                    "
                  >
                    {{ scope.row.deployStatus }}
                  </el-tag>
                  <el-tag
                    type="warning"
                    size="medium"
                    v-else-if="showStatusTag(scope.row) === 4"
                  >异常
                  </el-tag>
                  <el-tag
                    v-else-if="showStatusTag(scope.row) === 1"
                    size="medium"
                  >更新中
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160">
                <template slot-scope="scope">
                  <el-button
                    @click="serviceInstanceDetail(scope.row)"
                    type="text"
                    style="margin-right: 10px; padding: 0"
                  >
                    详情
                  </el-button>
                  <el-dropdown
                    trigger="click"
                    @command="
                      (command) => {
                        handleCommand(command, scope.row);
                      }
                    "
                    :hide-on-click="false"
                  >
                    <el-button type="text" style="padding: 0">
                      更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="configuration"
                      >配置
                      </el-dropdown-item>
                      <el-dropdown-item command="yaml">查看yaml</el-dropdown-item>
                      <el-dropdown-item command="update">升级</el-dropdown-item>
                      <el-dropdown-item command="rollback"
                      >回滚
                      </el-dropdown-item>
                      <!--                      <el-popconfirm-->
                      <!--                        title="确认删除服务实例？"-->
                      <!--                        @confirm="deleteServiceInfo(scope.row)"-->
                      <!--                      >-->
                      <!--                        <el-dropdown-item-->
                      <!--                          slot="reference"-->
                      <!--                          style="color: #f56c6c"-->
                      <!--                          >删除-->
                      <!--                        </el-dropdown-item>-->
                      <!--                      </el-popconfirm>-->
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="margin-top: 10px; float: right">
            <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="page.total"
              :page-size="page.pageSize"
              :page.sync="page"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>
    <div v-if="dialogVisible">
      <el-dialog
        :title="'服务:' + serviceInstance.appName + ' 详情'"
        :visible.sync="dialogVisible"
        width="70%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
      >
        <service-instance-detail-dialog
          :serviceInstance="serviceInstance"
        ></service-instance-detail-dialog>
      </el-dialog>
    </div>
    <div v-if="serviceSetUp">
      <el-dialog
        :title="'服务' + titleForDialog"
        :visible.sync="serviceSetUp"
        width="70%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
      >
        <service-instance-configuration
          :openType="openType"
          :deployId="deployId"
          ref="serviceInstanceSetUp"
        ></service-instance-configuration>
      </el-dialog>
    </div>
    <div v-if="rollbackDialog">
      <el-dialog
        title="服务回滚"
        :visible.sync="rollbackDialog"
        width="30%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        center
      >
        <service-instance-rollback-dialog
          :serviceInstance="serviceInstance"
          ref="rollbackDialogOperate"
        >
        </service-instance-rollback-dialog>
      </el-dialog>
    </div>
    <div v-if="yamlDialog">
      <el-dialog
        title="查看yaml"
        :visible.sync="yamlDialog"
        width="50%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :before-close="beforeCloseYamlDialog"
      >
        <div style="height: 60vh; overflow-y: auto">
          <codemirror v-model="yamlString" :options="cmOptions"/>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import ServiceInstanceDetailDialog from "@/views/ApplicationManage/ServiceInstanceDetailDialog.vue";
  import ServiceInstanceConfiguration from "@/views/ApplicationManage/ServiceInstanceConfiguration.vue";
  import ServiceInstanceRollbackDialog from "@/views/ApplicationManage/ServiceInstanceRollbackDialog.vue";
  import {getTenantId} from "@/utils/tenantId";
  import {codemirror} from "vue-codemirror";
  import "codemirror/lib/codemirror.css";
  import "codemirror/mode/yaml/yaml.js";

  export default {
    name: "ServiceList",
    components: {
      ServiceInstanceRollbackDialog,
      ServiceInstanceDetailDialog,
      ServiceInstanceConfiguration,
      codemirror,
    },
    data() {
      return {
        searchInput: "",
        tableData: [],
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0,
        },
        tmpPage: {
          pageSize: 10,
          pageNum: 1,
          filterKey: "",
          tenantId: "",
        },
        fullscreenLoading: false,
        timer: 0,
        dialogVisible: false,
        serviceInstance: {},
        selectInstanceList: [],
        openType: "",
        titleForDialog: "",
        deployId: "",
        serviceSetUp: false,
        rollbackDialog: false,
        isShowTooltip: false,
        yamlDialog: false,
        yamlString: "",
        cmOptions: {
          mode: "yaml", // 使用YAML模式
          theme: "default", // 使用默认主题
          lineNumbers: true, // 显示行号
          line: true, // 显示行高亮
          styleActiveLine: true, // 高亮当前行
          matchBrackets: true, // 括号匹配高亮
          autoCloseBrackets: true, // 自动闭合括号
          gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], // 显示行号和折叠标记
          foldGutter: true, // 启用折叠功能
          extraKeys: {"Ctrl-Space": "autocomplete"}, // 添加自动完成快捷键
          readOnly: true, // 禁止编辑
        },
      };
    },
    methods: {
      getYamlDetail(serviceInstance) {
        this.deployId = serviceInstance.id;
        this.$appManageApi.getYamlDetail(this.deployId).then((res) => {
          this.yamlString = res.data;
        });
        this.yamlDialog = true;
      },
      beforeCloseYamlDialog(done) {
        this.yamlDialog = false;
        this.yamlString = "";
        this.deployId = "";
        done();
      },
      onMouseOver(event) {
        const ev = event.target;
        const evWeight = ev.scrollWidth;
        const contentWidth = ev.clientWidth;
        if (evWeight > contentWidth) {
          this.isShowTooltip = false;
        } else {
          this.isShowTooltip = true;
        }
      },
      serviceInstanceDetail(row) {
        this.dialogVisible = true;
        this.serviceInstance = row;
      },
      getAllServiceInstance() {
        setTimeout(() => {
          this.tmpPage.tenantId = getTenantId();
          if (this.tmpPage.tenantId === undefined) {
            this.$router.push("/");
            this.$message.warning("数据出现问题，请稍后再试");
          } else {
            this.$appManageApi.listKubeDeploy(this.tmpPage).then((res) => {
              if (res && res.code === 200) {
                this.tableData = res.data.records.sort(
                  (ele1, ele2) =>
                    new Date(ele2.updateTime).getTime() -
                    new Date(ele1.updateTime).getTime()
                );
                this.page.total = res.data.total;
                this.getCurrentPageDeployStatus();
              }
            });
          }
        }, 500);
      },
      getCurrentPageDeployStatus() {
        let deployIds = [];
        this.tableData.forEach((ele) => {
          deployIds.push(ele.id);
        });
        this.$appManageApi
          .getDeployStatus(deployIds)
          .then((res) => {
            if (res && res.code === 200) {
              this.tableData.forEach((ele) => {
                let deployStatusEle = res.data.filter(
                  (element) => ele.id === element.deployId
                )[0];
                let tmpStatus = "";
                switch (deployStatusEle.status) {
                  case "NONE":
                    tmpStatus = "未部署";
                    break;
                  case "UPDATING":
                    tmpStatus = "更新中";
                    break;
                  case "RUNNING":
                    tmpStatus = "运行中";
                    break;
                  case "STOPPED":
                    tmpStatus = "已停止";
                    break;
                  case "ERROR":
                    tmpStatus = "异常";
                    break;
                  default:
                    tmpStatus = "未知";
                }
                ele.deployStatus = tmpStatus;
              });
            } else {
              clearInterval(this.timer);
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      changePage(currentPage) {
        this.page.currentPage = currentPage;
        this.tmpPage.pageNum = currentPage;
        this.getAllServiceInstance();
      },
      showStatusTag(row) {
        let tmpStatus = 0;
        switch (row.deployStatus) {
          case "未部署":
            tmpStatus = 0;
            break;
          case "更新中":
            tmpStatus = 1;
            break;
          case "运行中":
            tmpStatus = 2;
            break;
          case "已停止":
            tmpStatus = 3;
            break;
          case "异常":
            tmpStatus = 4;
            break;
          default:
            tmpStatus = 5;
        }
        return tmpStatus;
      },
      filterServiceInstanceList() {
        this.tmpPage.filterKey = this.searchInput;
        this.tmpPage.pageNum = 1;
        this.tmpPage.pageSize = 10;
        this.getAllServiceInstance();
      },
      tableSelectionChange(selectList) {
        this.selectInstanceList = selectList;
      },
      startSelectInstances() {
        if (!this.operateCheck()) {
          return;
        }
        const result = this.openFullScreen2();
        let flag = true;
        let doNotStartService = {};
        let deployIds = [];
        this.selectInstanceList.forEach((ele) => {
          if (
            ele.deployStatus === "更新中" ||
            ele.deployStatus === "运行中" ||
            ele.deployStatus === "异常"
          ) {
            doNotStartService = ele;
            flag = false;
          }
          deployIds.push(ele.id);
        });
        if (flag === false) {
          this.$message.error(
            "服务：" +
            doNotStartService.deployName +
            "状态为：" +
            doNotStartService.deployStatus +
            "，请取消勾选。"
          );
          return;
        }
        this.$appManageApi.startYamlDeploy(deployIds).then((res) => {
          if (res && res.code === 200) {
            this.$message.success(res.msg);
            this.getCurrentPageDeployStatus();
            this.selectInstanceList = [];
            this.$refs.multipleTable.clearSelection();
            result.close();
          }
        }).catch((error) => {
          result.close();
          this.$message.error(error.message);
        }).finally(() => {
          result.close();
        });
      },
      stopSelectInstances() {
        if (!this.operateCheck()) {
          return;
        }
        const result = this.openFullScreen2();
        let flag = true;
        let doNotStopService = {};
        let deployIds = [];
        this.selectInstanceList.forEach((ele) => {
          if (ele.deployStatus === "未部署" || ele.deployStatus === "已停止") {
            doNotStopService = ele;
            flag = false;
          }
          deployIds.push(ele.id);
        });
        if (flag === false) {
          this.$message.error(
            "服务：" +
            doNotStopService.deployName +
            "状态为：" +
            doNotStopService.deployStatus +
            "，请先取消勾选。"
          );
          return;
        }
        this.$appManageApi.stopYamlDeploy(deployIds).then((res) => {
          if (res && res.code === 200) {
            result.close();
            this.$message.success(res.msg);
            this.getCurrentPageDeployStatus();
            this.selectInstanceList = [];
            this.$refs.multipleTable.clearSelection();
          }
        }).catch((error) => {
          result.close();
          this.$message.error(error.message);
        }).finally(() => {
          result.close();
        });
      },
      openFullScreen2() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        return loading
      },
      // openFullScreen1() {
      //   this.fullscreenLoading = true;
      //   // setTimeout(() => {
      //   //   this.fullscreenLoading = false;
      //   // }, 2000);
      // },
      deleteSelectInstances() {
        if (!this.operateCheck()) {
          return;
        }
        let flag = true;
        let doNotDeleteService = {};
        let deployIds = [];
        this.selectInstanceList.forEach((ele) => {
          if (
            ele.deployStatus === "更新中" ||
            ele.deployStatus === "运行中" ||
            ele.deployStatus === "异常"
          ) {
            doNotDeleteService = ele;
            flag = false;
          }
          deployIds.push(ele.id);
        });
        if (flag === false) {
          this.$message.error(
            "服务：" +
            doNotDeleteService.deployName +
            "状态为：" +
            doNotDeleteService.deployStatus +
            "，请先停止服务。"
          );
          return;
        }
        this.$appManageApi
          .deleteYamlDeploy(deployIds)
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              this.selectInstanceList = [];
              this.$refs.multipleTable.clearSelection();
              this.tmpPage.pageSize = this.page.pageSize;
              this.tmpPage.pageNum = this.page.currentPage;
              this.getAllServiceInstance();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      operateCheck() {
        if (this.selectInstanceList.length === 0) {
          this.$message.warning("请选择数据之后执行操作");
          return false;
        }
        return true;
      },
      handleCommand(command, serviceInstance) {
        if (command === "configuration") {
          if (
            serviceInstance.deployStatus === "更新中" ||
            serviceInstance.deployStatus === "运行中" ||
            serviceInstance.deployStatus === "异常"
          ) {
            this.$message.warning(
              "服务：" +
              serviceInstance.deployName +
              "状态为：" +
              serviceInstance.deployStatus +
              "，请先停止服务。"
            );
            return;
          }
          this.openType = "configuration";
          this.titleForDialog = "配置";
          this.serviceSetUp = true;
          this.deployId = serviceInstance.id;
          this.$nextTick(() => {
            if (this.$refs.serviceInstanceSetUp !== undefined) {
              this.$refs.serviceInstanceSetUp.$on(
                "closeServiceSetUpDialog",
                this.closeServiceSetUpDialog
              );
            }
          });
        } else if (command === "update") {
          this.openType = "update";
          this.titleForDialog = "升级";
          this.serviceSetUp = true;
          this.deployId = serviceInstance.id;
          this.$nextTick(() => {
            if (this.$refs.serviceInstanceSetUp !== undefined) {
              this.$refs.serviceInstanceSetUp.$on(
                "closeServiceSetUpDialog",
                this.closeServiceSetUpDialog
              );
            }
          });
        } else if (command === "rollback") {
          this.rollbackDialog = true;
          this.serviceInstance = serviceInstance;
          this.$nextTick(() => {
            if (this.$refs.rollbackDialogOperate !== undefined) {
              this.$refs.rollbackDialogOperate.$on(
                "closeRollbackDialog",
                this.closeRollbackDialog
              );
            }
          });
        } else if (command === "yaml") {
          this.getYamlDetail(serviceInstance);
        }
      },
      deleteServiceInfo(serviceInstance) {
        if (
          serviceInstance.deployStatus === "更新中" ||
          serviceInstance.deployStatus === "运行中" ||
          serviceInstance.deployStatus === "异常"
        ) {
          this.$message.error(
            "服务：" +
            serviceInstance.deployName +
            "状态为：" +
            serviceInstance.deployStatus +
            "，请先停止服务。"
          );
          return;
        }
        this.$appManageApi
          .deleteYamlDeploy([serviceInstance.id])
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              this.selectInstanceList = [];
              this.$refs.multipleTable.clearSelection();
              this.tmpPage.pageSize = this.page.pageSize;
              this.tmpPage.pageNum = this.page.currentPage;
              this.getAllServiceInstance();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      closeServiceSetUpDialog() {
        this.serviceSetUp = false;
        this.$refs.serviceInstanceSetUp.$off("closeServiceSetUpDialog");
      },
      closeRollbackDialog() {
        this.rollbackDialog = false;
        this.$refs.rollbackDialogOperate.$off("closeRollbackDialog");
      },
    },
    mounted() {
      this.getAllServiceInstance();
      this.timer = setInterval(() => {
        this.getCurrentPageDeployStatus();
      }, 5000);
    },
    beforeDestroy() {
      clearInterval(this.timer);
    },
  };
</script>

<style lang="css" scoped>
  /*.el-button {*/
  /*  border-radius: 30px;*/
  /*  display: inline-block;*/
  /*  margin: 0 8px;*/
  /*}*/

  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #304156;
  }
</style>

<style>
  .tooltipClass {
    width: 300px;
  }
</style>
